package com.min.netty.listener;

import com.min.netty.codec.LogEventDecoder;
import com.min.netty.handler.Handler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.net.SocketOption;

/**
 * CREATE BY 2018/9/10
 *
 * @author sirmin
 */
public class LogEventListener {
    private final InetSocketAddress inetSocketAddress;
    private final EventLoopGroup eventExecutors;
    private final Bootstrap bootstrap;


    public LogEventListener(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
        eventExecutors = new NioEventLoopGroup();
        bootstrap = new Bootstrap().group(eventExecutors)
                .channel(NioDatagramChannel.class)
                .localAddress(inetSocketAddress)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<Channel>(){
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new LogEventDecoder())
                        .addLast(new Handler());
                    }
                });
    }

    public void stop() {
        eventExecutors.shutdownGracefully();
    }

    public void run() throws InterruptedException {
        final Channel channel = bootstrap.bind().syncUninterruptibly().channel();
        channel.closeFuture().sync();
    }
}
